package com.tool.payment.service.impl;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import com.tool.payment.enums.ProductEnum;
import com.tool.payment.model.PayOrder;
import com.tool.payment.model.PayParams;
import com.tool.payment.service.PaymentService;
import com.tool.payment.service.PaymentProxyService;
import com.tool.payment.spring.SpringContextHolder;

@Service
public class PaymentProxyServiceImpl implements PaymentProxyService {

	private static final Logger logger = org.slf4j.LoggerFactory.getLogger(PaymentProxyServiceImpl.class);
	
	@Override
	public Map<String, String> createOrder(String product,String mode,HttpServletRequest request) {
		String notifyUrl = "notify/" + product + "/" + mode;
		return getPaymentService(product,mode).createOrder(product,mode,notifyUrl,request);
	}
	
	@Override
	public Map<String, String> createOrder(PayParams params,HttpServletRequest request) {
		String product = params.getProduct();
		String mode = params.getMode();
		String notifyUrl = "notify/" + product + "/" + mode;
		return getPaymentService(product,mode).createOrder(notifyUrl,params,request);
	}
	
	@Override
	public String payNotify(String product, String mode, HttpServletRequest request) {
		return this.getPaymentService(product, mode).payNotify(request);
	}
	
	@Override
	public Map<String, String> refundOrder(PayParams params,HttpServletRequest request) {
		String product = params.getProduct();
		String mode = params.getMode();
		return this.getPaymentService(product, mode).refundOrder(params);
	}
	
	@Override
	public Map<String, PayOrder> reconciliation(PayParams params) {
		String product = params.getProduct();
		String mode = params.getMode();
		return this.getPaymentService(product, mode).reconciliation(params);
	}

	private PaymentService getPaymentService(String product, String mode) {
		PaymentService paymentService = null;
		if(product.equals(ProductEnum.WEIXIN.name)) {
			paymentService = SpringContextHolder.getBean(WeixinPaymentServiceImpl.class);
		} else if(product.equals(ProductEnum.ALIPAY.name)) {
			paymentService = SpringContextHolder.getBean(AlipayPaymentServiceImpl.class);
		}
		if(paymentService == null){
			logger.error("ProxyServiceImpl 没有匹配到代理的支付实现");
		}
		return paymentService;
	}
}
